//
//  UIButton+extension.m
//  MGPublic
//
//  Created by lhongl on 2025/11/4.
//

#import "UIButton+extension.h"

@implementation UIButton (extension)

#pragma mark - 设置样式和间距
- (void)setAdjustWithSpace:(CGFloat)space {
    CGFloat halfSpace = space / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -halfSpace, 0, halfSpace);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, halfSpace, 0, -halfSpace);
    self.contentEdgeInsets = UIEdgeInsetsMake(0, halfSpace,0, halfSpace);
}

#pragma mark - 设置样式和间距
- (void)setAdjustWithStyle:(MGButtonEdgeImageStyle)style space:(CGFloat)space{
    
    // 1. 得到imageView和titleLabel的宽、高
    CGFloat imageWith = self.imageView.image.size.width;
    CGFloat imageHeight = self.imageView.image.size.height;

    CGFloat labelWidth = self.titleLabel.intrinsicContentSize.width;
    CGFloat labelHeight = self.titleLabel.intrinsicContentSize.height;
    

    // 2. 声明全局的imageEdgeInsets和labelEdgeInsets
    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
    
    CGFloat halfSpace = space / 2.0;
    // 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
    switch (style) {
        case MGButtonEdgeImageStyleTop:{
            imageEdgeInsets = UIEdgeInsetsMake(-labelHeight - halfSpace, 0, 0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight - halfSpace, 0);
            self.contentEdgeInsets = UIEdgeInsetsMake((imageHeight + space) / 2.0, 0,(imageHeight + space) / 2.0, 0);
        }
            break;
        case MGButtonEdgeImageStyleLeft:{
            imageEdgeInsets = UIEdgeInsetsMake(0, -halfSpace, 0, halfSpace);
            labelEdgeInsets = UIEdgeInsetsMake(0, halfSpace, 0, -halfSpace);
            self.contentEdgeInsets = UIEdgeInsetsMake(0, halfSpace,0, halfSpace);
        }
            break;
        case MGButtonEdgeImageStyleBottom:{
            imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight - halfSpace, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(-imageHeight - halfSpace, -imageWith, 0, 0);
            self.contentEdgeInsets = UIEdgeInsetsMake((imageHeight + space) / 2.0, 0,(imageHeight + space) / 2.0, 0);
        }
            break;
        case MGButtonEdgeImageStyleRight:{
            imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + halfSpace, 0, -labelWidth - halfSpace);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith - halfSpace, 0, imageWith + halfSpace);
            self.contentEdgeInsets = UIEdgeInsetsMake(0, halfSpace,0, halfSpace);
        }
            break;
        default:
            break;
    }

    self.titleEdgeInsets = labelEdgeInsets;
    self.imageEdgeInsets = imageEdgeInsets;
}

@end
